/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.yipinsoft.modules.wechat.core.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.CacheUtils;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 微信oauth拦截器
 * @author liulin
 * @version 2017-10-23
 */
public class Oauth2Interceptor extends BaseService implements HandlerInterceptor {
	@Autowired
    private WxMpService wxService;
	
	private static final String WECHAT_OAUTH_CACHE = "wechatOauthCache";
	private static final String WECHAT_USER_CACHE = "wechatUserCache";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object handler) throws Exception {
		//如果使用session时，判断缓存中是否存在内容，如果存在则通过
		if(CacheUtils.get(WECHAT_USER_CACHE, request.getSession().getId()) != null) {
			return true;
		}
		
		String queryString = "";
		if (request.getQueryString() != null) {
			queryString = "?" + request.getQueryString().toString();
		}
		
		String url = request.getRequestURL().toString();
		String code = request.getParameter("code");
		//将Code放入缓存，如果该Code已经使用则不再使用
		if (code != null && CacheUtils.get(WECHAT_OAUTH_CACHE, code) != null) {
			return true;
		}
		try {
			if (code != null) {
				//如果代码不为空，那么则为redirect的请求，取得微信用户信息保存到session中
				WxMpOAuth2AccessToken wxMpOAuth2AccessToken  = wxService.oauth2getAccessToken(code);
				wxMpOAuth2AccessToken = wxService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
				WxMpUser wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
				//将Code放入缓存，如果该Code已经使用则不再使用
				CacheUtils.put(WECHAT_OAUTH_CACHE, code, code);
				//将wxMpUser存入缓存中，key为sessionId
				CacheUtils.put(WECHAT_USER_CACHE, request.getSession().getId(), wxMpUser);
				
				return true;
			}
			//oauth认证
			url = wxService.oauth2buildAuthorizationUrl(url + queryString, WxConsts.OAUTH2_SCOPE_USER_INFO, null);
			response.sendRedirect(url);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, 
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
			Object handler, Exception ex) throws Exception {
		
	}

}
